<?php

namespace App\Http\Middleware;

use App\Repositories\Eloquent\Repository;
use Closure;
use Encore\Admin\Facades\Admin;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CheckOwner
{
    use AuthorizesRequests;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $fun = $request->route()->getActionMethod();
        $repository = $request->route()->getController()->repository;
        if (in_array($fun, ['show', 'edit', 'update','destroy'])) {
            $id = current($request->route()->parameters);
            if ($fun == 'destroy'){
                $ids = Str::of($id)->explode(',');
            }else{
                $ids = [$id];
            }
            if(!$repository->isOwner(Admin::user(),$ids)){
                if ($request->pjax()) {
                    admin_toastr('不存在!', 'error');
                    return back();
                } elseif ($request->ajax()) {
                    return response()->json(['status' => false, 'message' => '不存在!']);
                }
            }
        }
        return $next($request);
    }
}
